<template>
  <div class="dialogBox">
    <el-dialog v-model="props.dialogVisible" :title="title" width="50%" :before-close="closeDialog">
      <el-form ref="ruleFormRef" :rules="rules" :model="form1" label-width="100px" size="default">
        <el-form-item label="模型类型" prop="modelType">
          <el-cascader
            v-model="modelType"
            :options="modelTypeOptions"
            :props="{ value: 'typeId', label: 'typeName', children: 'types' }"
            @change="handleChangeType"
          />
        </el-form-item>
        <el-form-item label="模型名称" prop="modelName">
          <el-input v-model="form1.modelName" />
        </el-form-item>
        <div class="form-input-box w50">
          <el-form-item label="模型版本号" prop="version">
            <el-input v-model="form1.version" />
          </el-form-item>
          <el-form-item label="模型单位" prop="unit">
            <el-input v-model="form1.unit" />
          </el-form-item>
        </div>
        <el-form-item label="模型说明" prop="modelDesc">
          <el-input v-model="form1.modelDesc" type="textarea" />
        </el-form-item>
        <div class="form-input-box2">
          <el-form-item label="模型程序包" prop="attachUrl">
            <el-input v-model="attachUrl" />
          </el-form-item>
          <el-upload
            v-model:file-list="fileList"
            class="upload-demo left-spacing"
            action="#"
            multiple
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="3"
            :on-exceed="handleExceed"
            :http-request="uploadFile"
            :show-file-list="false"
          >
            <el-button type="primary">上传文件</el-button>
          </el-upload>
          <!-- <el-button type="primary" @click="downloadBtn" class="left-spacing set-other-btn"
            >模型规范标准下载</el-button
          > -->
        </div>
        <div class="form-input-box">
          <div class="img-input">
            <el-form-item label="模型示意图" prop="sketchUrl">
              <el-input v-model="sketchUrl" />
            </el-form-item>
            <!-- <span class="img-input-item">上传图片</span> -->
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo left-spacing"
              action="#"
              multiple
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :limit="3"
              :on-exceed="handleExceed"
              :http-request="uploadPicFile"
              :data="{ picType: 0 }"
              :show-file-list="false"
            >
              <el-button type="primary">上传图片</el-button>
            </el-upload>
          </div>
          <div class="img-input">
            <el-form-item label="模型概化图" prop="genUrl">
              <el-input v-model="genUrl" />
            </el-form-item>
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo left-spacing"
              action="#"
              multiple
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :limit="3"
              :on-exceed="handleExceed"
              :data="{ picType: 1 }"
              :http-request="uploadPic2File"
              :show-file-list="false"
            >
              <el-button type="primary">上传图片</el-button>
            </el-upload>
          </div>
        </div>
        <el-row :gutter="20" class="magerTop">
          <el-col :span="25">
            <el-row>
              <el-col>
                <el-form-item label="模型参数" class="row-flex" prop="params">
                  <el-input
                    style="width: 150px"
                    class="short-area"
                    type="textarea"
                    rows="9"
                    v-model="form1.params"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="25">
            <el-row>
              <el-col :span="24">
                <el-form-item label="参数说明" class="row-flex" prop="paramsDesc">
                  <el-input
                    style="width: 150px"
                    class="short-area"
                    type="textarea"
                    rows="9"
                    v-model="form1.paramsDesc"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="25">
            <el-row>
              <el-col :span="24">
                <el-form-item label="模型输入" class="row-flex" prop="inData">
                  <el-input
                    style="width: 150px"
                    class="short-area"
                    type="textarea"
                    rows="9"
                    v-model="form1.inData"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="25">
            <el-row>
              <el-col :span="24">
                <el-form-item label="模型输出" class="row-flex" prop="outData">
                  <el-input
                    style="width: 150px"
                    class="short-area"
                    type="textarea"
                    rows="9"
                    v-model="form1.outData"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="25">
            <el-row>
              <el-col :span="24">
                <el-form-item label="模型适应性说明" class="row-flex" prop="suitability">
                  <el-input
                    style="width: 150px"
                    class="short-area"
                    type="textarea"
                    rows="9"
                    v-model="form1.suitability"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="registerBtn">{{
            props.modelId ? '修改' : '注册'
          }}</el-button>
          <el-button @click="closeDialog()">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, toRefs, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  registe,
  editModel,
  resourcesUp,
  pictureUp,
  getModelType,
  getModelDetails
} from '@/services/modules/home'

const rules = {
  modelType: [{ required: true, message: '请输入模型类型', trigger: 'blur' }],
  modelName: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入模型单位', trigger: 'blur' }],
  modelDesc: [{ required: true, message: '请输入模型说明', trigger: 'blur' }],
  attachId: [{ required: true, message: '请上传附件', trigger: 'blur' }],
  sketchId: [{ required: true, message: '请上传示意图', trigger: 'blur' }],
  genId: [{ required: true, message: '请上传概化图', trigger: 'blur' }],
  params: [{ required: true, message: '请输入模型参数', trigger: 'blur' }],
  paramsDesc: [{ required: true, message: '请输入参数说明', trigger: 'blur' }],
  inData: [{ required: true, message: '请输入输入', trigger: 'blur' }],
  outData: [{ required: true, message: '请输入输出', trigger: 'blur' }],
  suitability: [{ required: true, message: '请输入适应性说明', trigger: 'blur' }]
}
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  modelId: Number
})
// const { modelId } = toRefs(props)

const title = ref('模型修改')
let modelType = ref([])
let attachUrl = ref('')
let sketchUrl = ref('')
let genUrl = ref('')
let form1 = reactive({
  modelType: '', //模型类型
  modelName: '', //模型名称
  version: '', //版本号
  unit: '', //模型单位
  modelDesc: '', //模型说明
  attachId: '', //附件
  sketchId: '', //示意图
  genId: '', //概化图
  params: '', //模型参数
  paramsDesc: '', //参数说明
  inData: '', //输入
  outData: '', //输出
  suitability: '' //适应性说明
})
const ruleFormRef = ref(null)
// const downloadBtn = () => {
//   ElMessage({
//     message: '下载成功.',
//     type: 'success'
//   })
// }
// const { region, name, version } = toRefs(form);
const emit = defineEmits(['closeDialog'])
const handleExceed = () => {}
const handlePreview = () => {}
const handleRemove = () => {}
const beforeRemove = () => {}

const closeDialog = () => {
  ruleFormRef.value.resetFields()
  modelType.value = []
  attachUrl.value = ''
  sketchUrl.value = ''
  genUrl.value = ''
  emit('closeDialog', false)
}
//选择模型类型
const handleChangeType = (value) => {
  form1.modelType = modelType.value[modelType.value.length - 1]
}
//上传
// const resourcesUp = ref(apiUrl + '/mxpt/resources/attached/upload')
// 重写上传程序
async function uploadFile(params) {
  console.log(params, '上传文件')
  var { file } = params
  var formData = new FormData()
  formData.append('file', file)
  let res = await resourcesUp(formData)
  if (res.code == 200) {
    form1.attachId = res.data.id
    attachUrl.value = res.data.url
  }
}
async function uploadPicFile(params) {
  var { file } = params
  var formData = new FormData()
  formData.append('file', file)
  formData.append('picType', 0)
  let res = await pictureUp(formData)
  if (res.code == 200) {
    form1.sketchId = res.data.id
    sketchUrl.value = res.data.url
  }
}
async function uploadPic2File(params) {
  var { file } = params
  var formData = new FormData()
  formData.append('file', file)
  formData.append('picType', 1)
  let res = await pictureUp(formData)
  if (res.code == 200) {
    form1.genId = res.data.id
    genUrl.value = res.data.url
  }
}
const registerBtn = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      if (props.modelId > 0) {
        form1.id = props.modelId
        editModel({ ...form1 }).then(async (res) => {
          if (res.code === 200) {
            closeDialog()
          }
        })
      } else {
        form1.id = undefined
        registe({ ...form1 }).then(async (res) => {
          if (res.code === 200) {
            closeDialog()
          }
        })
      }
    } else {
      return
    }
  })
}

const modelTypeOptions = ref([])
let listProps = ref({
  value: 'specialId',
  label: 'specialName',
  children: 'types'
})
//获取模型类型
function initData() {
  return new Promise((resolve, reject) => {
    getModelType().then((res) => {
      if (res.code === 200) {
        modelTypeOptions.value = JSON.parse(
          JSON.stringify(res.data)
            .replace(/"specialName"/g, '"typeName"')
            .replace(/"specialId"/g, '"typeId"')
        )
      }
    })
  })
}
//获取模型详情
function getModel() {
  return new Promise((resolve, reject) => {
    getModelDetails({
      modelId: props.modelId
    }).then((res) => {
      if (res.code === 200) {
        let _data = res.data
        console.log(res.data, '模型参数modelParams')

        setTimeout(() => {
          // form1 = { ..._data }
          form1 = Object.assign(form1, _data)

          form1.params = regStr(form1.params)

          form1.paramsDesc = regStr(form1.paramsDesc)
          form1.inData = regStr(form1.inData)
          form1.outData = regStr(form1.outData)
          form1.suitability = regStr(form1.suitability)
        }, 100)
        setModelType(res.data?.modelType)
        attachUrl.value = _data.attachUrl
        sketchUrl.value = _data.sketchUrl
        genUrl.value = _data.genUrl
      }
    })
  })
}
const regStr = (value) => {
  return value ? value.replace(/\\n/g, '\n') : ''
}
const setModelType = (id) => {
  //读取详情之后，根据modelType回显模型类型
  let result = []
  let _modelType = modelTypeOptions.value
  for (let i = 0; i < _modelType.length; i++) {
    for (let j = 0; j < _modelType[i].types.length; j++) {
      if (id == _modelType[i].types[j].typeId) {
        result = [_modelType[i].typeId, id]
      }
    }
  }
  modelType.value = result
}

watch(
  () => props.dialogVisible,
  (newValue, oldValue) => {
    console.log(newValue, oldValue)
    if (newValue) {
      if (props.modelId > 0) {
        title.value = '模型修改'
        getModel()
      } else {
        title.value = '模型注册'
        form1.id = undefined
        Object.keys(form1).forEach((key) => {
          form1[key] = ''
        })
      }
    }
  }
)

onMounted(async () => {
  initData()
})
</script>

<style lang="less" scoped>
.dialogBox {
  :deep(.el-dialog__body) {
    padding-bottom: 0;
  }
  .el-dialog__header {
    border-bottom: 1px solid rgb(14, 13, 13);
  }

  .form-input-box {
    display: flex;
    justify-content: space-between;
    &.w50 {
      :deep(.el-form-item) {
        width: 50%;
      }
    }
    .img-input {
      display: flex;
    }
  }

  .el-button--primary {
    margin-left: 20px;
    background-color: rgba(22, 155, 213, 1);
  }

  .form-input-box2 {
    display: flex;

    .set-other-btn {
      border: solid 1px rgb(21, 13, 237);
      background-color: rgb(21, 13, 237);
    }
  }
  .short-area {
    width: 90%;
    margin-top: 20px;
  }

  .row-flex {
    flex-direction: column;
    white-space: nowrap;
    // align-items: center;
  }

  .el-col-4 {
    max-width: 20%;
  }

  .magerTop {
    margin-top: 5px;
    :deep(.el-col-25) {
      width: 18%;
      margin-right: 2%;
      padding: 0 !important;
    }
    :deep(.el-textarea__inner) {
      resize: none;
    }
  }
}
</style>
